<?php

class ImageHandler {
	// 保存存储位置
	private $_savedir;
	private $_maxdim;
	private function _check_savedir() {
		$path = $_SERVER["DOCUMENT_ROOT"].$this->_savedir;
		if (!is_dir($path)) {
			if (!mkdir($path, 0777, true)) {
				throw new Exception("Cannot create image folder.");
			}
		}
	}
	private function _rename_file($ext) {
		return time()."_".mt_rand(1000, 9999)."$ext";
	}
	private function _get_file_ext($type) {
		switch ($type) {
			case 'image/gif':
				return ".gif";
			case 'image/jpeg':
			case 'image/pjpeg':
				return ".jpg";
			case 'image/png':
				return ".png";
			default:
				throw new Exception("Unsupported type.");
		}
	}
	private function _get_new_dims($img) {
		list($src_w, $src_h) = getimagesize($img);
		list($max_w, $max_h) = $this->_maxdim;
		if ($src_w > $max_w || $src_h > $max_h) {
			$s = min($max_w / $src_w, $max_h / $src_h);
		} else {
			$s = 1;
		}
		$new_w = $s * $src_w;
		$new_h = $s * $src_h;
		return array ($new_w, $new_h, $src_w, $src_h);
	}
	private function _get_img_functions($path) {
		$info = getimagesize($path);
		switch ($info["mime"]) {
			case 'image/jpeg':
			case 'image/pjpeg':
				return array('imagecreatefromjpeg', 'imagejpeg');
				break;
			case 'image/gif':
				return array('imagecreatefromgif', 'imagegif');
				break;
			case 'image/png':
				return array('imagecreatefrompng', 'imagepng');
				break;
			default:
				return FALSE;
		}
	}
	private function _do_img_resize($img) {
		$sz = $this->_get_new_dims($img);
		$f = $this->_get_img_functions($img);
		$src = $f[0]($img);
		$n = imagecreatetruecolor($sz[0], $sz[1]);
		if (imagecopyresampled($n, $src, 0, 0, 0, 0, $sz[0], $sz[1], $sz[2], $sz[3])) {
			imagedestroy($src);
			if ($n && $f[1]($n, $img)) {
				imagedestroy($n);
			} else {
				throw new Exception("Cannot save resampled image.");
			}
		} else {
			throw new Exception("Cannot resample image.");
		}

	}
	// 用图片最终的存储位置来初始化
	public function __construct($save_dir, $md=array(350, 240)) {
		$this->_savedir = $save_dir;
		$this->_maxdim = $md;
	}
	public function process_uploaded($file, $rename=true) {
		// list 是一种语言结构
		list($name, $type, $tmp, $err, $size) = array_values($file);
		if ($err != UPLOAD_ERR_OK) {
			// 上传失败则抛出异常
			throw new Exception("Upload failed.");
			return;
		}
		$filepath = $this->_savedir;
		$absolute = $_SERVER["DOCUMENT_ROOT"].$filepath;
		$this->_check_savedir();
		$this->_do_img_resize($tmp);
		if ($rename) {
			$ext = $this->_get_file_ext($type);
			$name = $this->_rename_file($ext);
		}
		if (!move_uploaded_file($tmp, $absolute."/$name")) {
			throw new Exception("Cannot move uploaded file.");
			return;
		}
		// 返回图片的网址, 而不是在文件系统中的地址
		return "http://".$_SERVER["HTTP_HOST"].$filepath."/$name";
	}
}
?>